/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.workflowDesign.service.impl;

import com.koron.workflow.common.bean.PageBean;
import com.koron.workflow.common.bean.StaffBean;
import com.koron.workflow.common.util.BusinessCode;
import com.koron.workflow.common.util.DisposeBeanUtil;
import com.koron.workflow.common.util.WorkflowUtil;
import com.koron.workflow.workflowDesign.bean.ProcessSetBean;
import com.koron.workflow.workflowDesign.bean.ProcessSetQueryBean;
import com.koron.workflow.workflowDesign.bean.ProcessUpdateBean;
import com.koron.workflow.workflowDesign.mapper.ProcessMapper;
import com.koron.workflow.workflowDesign.mapper.ProcessSetMapper;
import com.koron.workflow.workflowDesign.service.ProcessSetService;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.swan.bean.MessageBean;

import java.util.List;
import java.util.Map;

/**
 * 模版组管理
 */
@Service
public class ProcessSetServiceImpl implements ProcessSetService {
    private static final Logger logger = LoggerFactory.getLogger(ProcessSetServiceImpl.class);

    @TaskAnnotation("queryForList")
    @Override
    public PageBean<ProcessSetQueryBean> queryForList(SessionFactory factory, StaffBean user, String code, String name, Integer status, Integer page, Integer pageSize) {
        ProcessSetMapper mapper = factory.getMapper(ProcessSetMapper.class);
        // 根据用户帐号 查询系统管理员ID
        String administratorId = mapper.queryAdminIdByUsercode(user.getAccount());
        List<ProcessSetQueryBean> list = mapper.queryForList(administratorId, code, name, status, page, pageSize);
        Integer total = null;
        if (page != null || pageSize != null) {
            total = mapper.countQueryForList(administratorId, code, name, status);
        }
        return new PageBean<>(list, total);
    }

    @TaskAnnotation("queryForObject")
    @Override
    public ProcessSetQueryBean queryForObject(SessionFactory factory, String id) {
        return factory.getMapper(ProcessSetMapper.class).queryForObject(id);
    }

    @TaskAnnotation("save")
    @Override
    public MessageBean save(SessionFactory factory, StaffBean user, ProcessSetBean bean) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        try {
            if (StringUtils.isEmpty(bean.getName()) || StringUtils.isEmpty(bean.getCode()) ||
                    StringUtils.isEmpty(bean.getDescription()) || StringUtils.isEmpty(bean.getAppId()) ||
                    StringUtils.isEmpty(bean.getStatus())) {
                msg.setCode(BusinessCode.EMPTY_PARAM.getCode());
                msg.setDescription(BusinessCode.EMPTY_PARAM.getDescription());
                return msg;
            }
            DisposeBeanUtil.disposeInsert(user, bean);
            ProcessSetMapper mapper = factory.getMapper(ProcessSetMapper.class);
            // 验证 code 是否已经存在
            if (mapper.verifyCode(bean.getCode(), bean.getAppId(), null) > 0) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("当前应用下该模版组编号已存在");
                return msg;
            }
            if (mapper.insert(bean) != 1) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription(BusinessCode.FAILURE.getDescription());
                return msg;
            }
            // 验证当前关联应用该用户是否有设计权限
            if (mapper.queryDesignApp(user.getAccount(), bean.getAppId()) != 1) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("当前用户没有选择应用的设计权限!");
                return msg;
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error("模版组管理复制失败", e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @TaskAnnotation("update")
    @Override
    public MessageBean update(SessionFactory factory, StaffBean user, ProcessSetBean bean) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        try {
            if (StringUtils.isEmpty(bean.getId())) {
                msg.setCode(BusinessCode.EMPTY_PARAM.getCode());
                msg.setDescription("没有获取到当前业务ID");
                return msg;
            }
            if (StringUtils.isEmpty(bean.getName()) || StringUtils.isEmpty(bean.getCode()) ||
                    StringUtils.isEmpty(bean.getDescription()) || StringUtils.isEmpty(bean.getAppId()) ||
                    StringUtils.isEmpty(bean.getStatus())) {
                msg.setCode(BusinessCode.EMPTY_PARAM.getCode());
                msg.setDescription(BusinessCode.EMPTY_PARAM.getDescription());
                return msg;
            }
            DisposeBeanUtil.disposeUpdate(user, bean);
            ProcessSetMapper mapper = factory.getMapper(ProcessSetMapper.class);
            // 验证 code 是否已经存在
            if (mapper.verifyCode(bean.getCode(), bean.getAppId(), bean.getId()) > 0) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("当前应用下该模版组编号已存在");
                return msg;
            }
            if (mapper.update(bean) != 1) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription(BusinessCode.FAILURE.getDescription());
                return msg;
            }
            // 验证当前关联应用该用户是否有设计权限
            if (mapper.queryDesignApp(user.getAccount(), bean.getAppId()) != 1) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("当前用户没有选择应用的设计权限!");
                return msg;
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error("模版组管理修改失败", e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @TaskAnnotation("delete")
    @Override
    public MessageBean delete(SessionFactory factory, String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        try {
            ProcessSetMapper mapper = factory.getMapper(ProcessSetMapper.class);
            // 根据processId删除
            mapper.deleteHistorybills(id);
            // 根据模版组ID删除 模版
            mapper.deleteProcess(id);
            // 根据ID删除 模版组管理
            if (mapper.delete(id) != 1) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription(BusinessCode.FAILURE.getDescription());
                return msg;
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error("模版组管理删除失败", e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @TaskAnnotation("copyProcessSet")
    @Override
    public MessageBean copyProcessSet(SessionFactory factory, StaffBean user, String copyId, String code, String name) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        try {
            ProcessSetMapper mapper = factory.getMapper(ProcessSetMapper.class);
            ProcessSetQueryBean bean = mapper.queryForObject(copyId);
            if (bean == null) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("该模版组已被删除");
                return msg;
            }
            // 验证 code 是否已经存在
            if (mapper.verifyCode(code, bean.getAppId(), null) > 0) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("当前应用下该模版组编号已存在");
                return msg;
            }
            // 复制后的模版组id
            String id = WorkflowUtil.getObjectId();
            // 根据ID复制 模版组管理
            if (mapper.copyProcessSet(copyId, id, code, name) != 1) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription(BusinessCode.FAILURE.getDescription());
                return msg;
            }

            // 复制模版组下的所有模版
            List<ProcessUpdateBean> processBeans = mapper.queryAllProcess(copyId);
            if (processBeans != null && processBeans.size() > 0) {
                for (ProcessUpdateBean updateBean : processBeans) {
                    updateBean.setId(WorkflowUtil.getObjectId());
                    updateBean.setSetId(id);
                    // 清空发布信息
                    updateBean.setDefId(null);
                }
                // 批量新增 模版管理
                factory.getMapper(ProcessMapper.class).insertBatch(processBeans);
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error("模版组管理复制失败", e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @TaskAnnotation("queryDesignAppList")
    @Override
    public List<Map> queryDesignAppList(SessionFactory factory, StaffBean user) {
        ProcessSetMapper mapper = factory.getMapper(ProcessSetMapper.class);
        // 根据用户帐号 查询系统管理员ID
        String administratorId = mapper.queryAdminIdByUsercode(user.getAccount());
        // 根据系统管理员ID 查询用户有设计权限的应用列表
        List<Map> list = mapper.queryDesignAppList(administratorId);
        return list;
    }
}
